#ifndef MUXER
#define MUXER

#include "format.h"

namespace lcf
{
    // 媒体封装
    class Muxer : public Format
    {
    public:
        Muxer() : srcVideoTimeBase_(nullptr),
                  srcAudioTimeBase_(nullptr),
                  beginVideoPts_(-1),
                  beginAudioPts_(-1)
        {
        }
        ~Muxer()
        {
            std::unique_lock<std::mutex> lock(mtx_);
            if (srcVideoTimeBase_)
                delete srcVideoTimeBase_;
            srcVideoTimeBase_ = nullptr;
            if (srcAudioTimeBase_)
                delete srcAudioTimeBase_;
            srcAudioTimeBase_ = nullptr;
        }
        // 打开封装
        static AVFormatContext *Open(const char *url,
                                     AVCodecParameters *videoPara = nullptr,
                                     AVCodecParameters *audioPara = nullptr);

        bool WriteHead();

        bool Write(AVPacket *pkt);

        bool WriteEnd();

        // 音视频时间基础
        void SetSrcVideoTimeBase(AVRational *tb)
        {
            if (!tb)
                return;
            std::unique_lock<std::mutex> lock(mtx_);
            if (!srcVideoTimeBase_)
                srcVideoTimeBase_ = new AVRational();
            *srcVideoTimeBase_ = *tb;
        }
        void SetSrcAudioTimeBase(AVRational *tb)
        {
            if (!tb)
                return;
            std::unique_lock<std::mutex> lock(mtx_);
            if (!srcAudioTimeBase_)
                srcAudioTimeBase_ = new AVRational();
            *srcAudioTimeBase_ = *tb;
        }

    private:
        AVRational *srcVideoTimeBase_;
        AVRational *srcAudioTimeBase_;
        long long beginVideoPts_; // 原视频开始时间
        long long beginAudioPts_; // 原音频开始时间
    };

}

#endif